<template>
  <div class="student-analysis-container">
    <div class="period-selector">
      <el-radio-group v-model="period" @change="handlePeriodChange">
        <el-radio-button label="day">当日</el-radio-button>
        <el-radio-button label="week">本周</el-radio-button>
      </el-radio-group>
    </div>
    
    <!-- 新增总览卡片 -->
    <el-row :gutter="16">
      <el-col :span="24">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>系统总览</span>
            </div>
          </template>
          <el-row :gutter="16">
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-value">{{ studentData.totalStudents || 0 }}</div>
                <div class="stat-label">学生总数</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-value">{{ studentData.classStats?.length || 0 }}</div>
                <div class="stat-label">班级总数</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card">
                <div class="stat-value">{{ teacherData.moduleStats?.length || 0 }}</div>
                <div class="stat-label">学科总数</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="16" style="margin-top: 16px;">
      <!-- 教师使用统计 -->
      <el-col :span="24">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>教师使用统计</span>
            </div>
          </template>
          <el-row :gutter="16">
            <el-col :span="12">
              <div ref="teacherUsageChart" class="chart-container"></div>
            </el-col>
            <el-col :span="12">
              <div ref="teacherModuleChart" class="chart-container"></div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 学生使用统计 -->
      <el-col :span="24" style="margin-top: 16px;">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>学生使用统计</span>
            </div>
          </template>
          <el-row :gutter="16">
            <el-col :span="12">
              <div ref="studentUsageChart" class="chart-container"></div>
            </el-col>
            <el-col :span="12">
              <div ref="studentModuleChart" class="chart-container"></div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import { getTeacherUsageStats, getStudentUsageStats } from '@/api/StatisticsAPI';

export default {
  name: 'StudentAnalysis',
  setup() {
    // 数据状态
    const period = ref('week');
    const loading = ref(false);
    
    // 图表引用
    const teacherUsageChart = ref(null);
    const teacherModuleChart = ref(null);
    const studentUsageChart = ref(null);
    const studentModuleChart = ref(null);
    
    // 图表实例
    let teacherUsageInstance = null;
    let teacherModuleInstance = null;
    let studentUsageInstance = null;
    let studentModuleInstance = null;
    
    // 教师数据
    const teacherData = reactive({
      dailyStats: [],
      moduleStats: []
    });
    
    // 学生数据
    const studentData = reactive({
      dailyStats: [],
      moduleStats: [],
      totalStudents: 0,
      classStats: []
    });
    
    // 初始化图表
    const initCharts = () => {
      // 初始化教师使用统计图表
      teacherUsageInstance = echarts.init(teacherUsageChart.value);
      teacherUsageInstance.setOption({
        title: {
          text: '教师使用次数统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value',
          name: '使用次数'
        },
        series: [
          {
            name: '使用次数',
            type: 'bar',
            data: [],
            itemStyle: {
              color: '#4e79a7'
            }
          }
        ]
      });
      
      // 初始化教师模块分布图表
      teacherModuleInstance = echarts.init(teacherModuleChart.value);
      teacherModuleInstance.setOption({
        title: {
          text: '教师活跃板块分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: []
        },
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: []
          }
        ]
      });
      
      // 初始化学生使用统计图表
      studentUsageInstance = echarts.init(studentUsageChart.value);
      studentUsageInstance.setOption({
        title: {
          text: '学生使用次数统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value',
          name: '使用次数'
        },
        series: [
          {
            name: '使用次数',
            type: 'bar',
            data: [],
            itemStyle: {
              color: '#59a14f'
            }
          }
        ]
      });
      
      // 初始化学生模块分布图表
      studentModuleInstance = echarts.init(studentModuleChart.value);
      studentModuleInstance.setOption({
        title: {
          text: '学生活跃板块分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: []
        },
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: []
          }
        ]
      });
      
      // 监听窗口调整大小事件
      window.addEventListener('resize', handleResize);
    };
    
    // 窗口大小变化时重绘图表
    const handleResize = () => {
      teacherUsageInstance && teacherUsageInstance.resize();
      teacherModuleInstance && teacherModuleInstance.resize();
      studentUsageInstance && studentUsageInstance.resize();
      studentModuleInstance && studentModuleInstance.resize();
    };
    
    // 更新教师使用统计图表
    const updateTeacherUsageChart = () => {
      const dates = teacherData.dailyStats.map(item => item.date);
      const counts = teacherData.dailyStats.map(item => item.count);
      
      teacherUsageInstance.setOption({
        xAxis: {
          data: dates
        },
        series: [
          {
            data: counts
          }
        ]
      });
    };
    
    // 更新教师模块分布图表
    const updateTeacherModuleChart = () => {
      const moduleData = teacherData.moduleStats.map(item => ({
        name: item.module,
        value: item.count
      }));
      
      teacherModuleInstance.setOption({
        legend: {
          data: moduleData.map(item => item.name)
        },
        series: [
          {
            data: moduleData
          }
        ]
      });
    };
    
    // 更新学生使用统计图表
    const updateStudentUsageChart = () => {
      const dates = studentData.dailyStats.map(item => item.date);
      const counts = studentData.dailyStats.map(item => item.count);
      
      studentUsageInstance.setOption({
        xAxis: {
          data: dates
        },
        series: [
          {
            data: counts
          }
        ]
      });
    };
    
    // 更新学生模块分布图表
    const updateStudentModuleChart = () => {
      const moduleData = studentData.moduleStats.map(item => ({
        name: item.module,
        value: item.count
      }));
      
      studentModuleInstance.setOption({
        legend: {
          data: moduleData.map(item => item.name)
        },
        series: [
          {
            data: moduleData
          }
        ]
      });
    };
    
    // 加载教师使用数据
    const loadTeacherData = async () => {
      try {
        loading.value = true;
        const response = await getTeacherUsageStats(period.value);
        
        if (response && response.data && response.data.success) {
          teacherData.dailyStats = response.data.data.dailyStats || [];
          teacherData.moduleStats = response.data.data.moduleStats || [];
          
          // 更新图表
          updateTeacherUsageChart();
          updateTeacherModuleChart();
        } else {
          ElMessage.error('获取教师使用统计数据失败');
        }
      } catch (error) {
        console.error('获取教师使用统计数据出错:', error);
        ElMessage.error('获取教师使用统计数据失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 加载学生使用数据
    const loadStudentData = async () => {
      try {
        loading.value = true;
        const response = await getStudentUsageStats(period.value);
        
        if (response && response.data && response.data.success) {
          studentData.dailyStats = response.data.data.dailyStats || [];
          studentData.moduleStats = response.data.data.moduleStats || [];
          studentData.totalStudents = response.data.data.totalStudents || 0;
          studentData.classStats = response.data.data.classStats || [];
          
          // 更新图表
          updateStudentUsageChart();
          updateStudentModuleChart();
        } else {
          ElMessage.error('获取学生使用统计数据失败');
        }
      } catch (error) {
        console.error('获取学生使用统计数据出错:', error);
        ElMessage.error('获取学生使用统计数据失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 加载所有数据
    const loadAllData = () => {
      loadTeacherData();
      loadStudentData();
    };
    
    // 周期变化处理
    const handlePeriodChange = () => {
      loadAllData();
    };
    
    // 组件挂载时
    onMounted(() => {
      initCharts();
      loadAllData();
    });
    
    // 组件卸载时
    onUnmounted(() => {
      window.removeEventListener('resize', handleResize);
      teacherUsageInstance && teacherUsageInstance.dispose();
      teacherModuleInstance && teacherModuleInstance.dispose();
      studentUsageInstance && studentUsageInstance.dispose();
      studentModuleInstance && studentModuleInstance.dispose();
    });
    
    // 监视周期变化
    watch(() => period.value, (newValue) => {
      loadAllData();
    });
    
    return {
      period,
      loading,
      teacherUsageChart,
      teacherModuleChart,
      studentUsageChart,
      studentModuleChart,
      handlePeriodChange,
      studentData,
      teacherData
    };
  }
};
</script>

<style scoped>
.student-analysis-container {
  padding: 24px;
}

.period-selector {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
}

.chart-container {
  height: 400px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.stat-card {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}
</style> 